import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';

// import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/course_class_bean.dart' hide ClassCourseBean;
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'course_class_bean/class_course_bean.dart';

class ClassCourseWidget extends StatefulWidget {
  final List<ClassCourseListItemBean> selectClassListBeanIndex;

  ///是否从编辑用户进入 （无论是否选择都可以确定）
  final bool fromEditUser;

  const ClassCourseWidget(
      {Key key, this.selectClassListBeanIndex, this.fromEditUser})
      : super(key: key);

  @override
  _ClassCourseWidgetState createState() => _ClassCourseWidgetState();

  ///跳转方法
  static Future<List<ClassCourseListItemBean>> navigatorPush(
      BuildContext context,
      List<ClassCourseListItemBean> selectClassListBeanIndex,
      {bool isFromEditUser}) {
    return RouterUtils.routeForFutureResult<List<ClassCourseListItemBean>>(
      context,
      ClassCourseWidget(
        selectClassListBeanIndex: selectClassListBeanIndex,
        fromEditUser: isFromEditUser ?? false,
      ),
    );
  }
}

class _ClassCourseWidgetState extends State<ClassCourseWidget> {
  List<ClassCourseListItemBean> mList;
  final String _classType = "03";
  bool isLightUp = false; //确认按钮是否亮起
  bool isSelectCourse = false; //确认按钮是否亮起
  List<String> selectCourseIndex = new List(); //选中的行
  List<TextEditingController> _editCourseListController =
      new List<TextEditingController>();
  List<ClassCourseListItemBean> listClassItemBean = new List();

  // TextEditingController _editCourseController;
  List<ClassCourseListItemBean> mAddRecordClassList = List();
  CommonListPageWidgetState mState;

  List<ClassCourseListItemBean> selectListCourseItemBean = new List();
  String roleId = UserRepository.getInstance()?.userData?.comUser?.roleid;
  String searchName;
  @override
  void initState() {
    super.initState();
    mList = List<ClassCourseListItemBean>();
    if(widget?.selectClassListBeanIndex!=null){
      selectCourseIndex =
          (widget?.selectClassListBeanIndex ?? []).map((e) => e.id).toList();
    }
    checkSave();
  }

  // @override
  // void dispose() {
  //   _editCourseController.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            _toTopBarWidget(),
            Padding(
              padding: const EdgeInsets.only(left: 7, right: 7, top: 10),
              child: _searchDepartmentWidget(),
            ),
            SizedBox(
              height: 10,
            ),
            if (roleId == "99")
              //点击添加一行
              _addCourseListWidget(),
            //课程list
            _courseClassListWidget(),
          ],
        ),
      ),
    );
  }

  Widget _courseClassListWidget() {
    Widget divider = Divider(
      color: Colors.blue,
    );
    return Expanded(
      child: CommonListPageWidget<ClassCourseListItemBean, ClassCourseBean>(
        enablePullUp: false,
        enablePullDown: true,
        queryMapFunc: (int page) => {
          "authId": UserRepository.getInstance().authId ?? "",
          "name":searchName??"",
          "type": _classType,
        },
        parseDataFunc: (VgHttpResponse resp) {
          ClassCourseBean bean = ClassCourseBean.fromMap(resp?.data);
          bean?.data?.removeWhere((element) =>
              element == null ||
              StringUtils.isEmpty(element.id) ||
              StringUtils.isEmpty(element.name));
          if(selectCourseIndex!=null&&selectCourseIndex.length>0&&bean.data!=null&&bean.data.length>0){
            List<ClassCourseListItemBean> newList=List();
            int i = 0;
            for (ClassCourseListItemBean element in bean.data) {
              if (selectCourseIndex.contains(element.id)) {
                newList.insert(i++, element);
              }else{
                newList.add(element);
              }

            }
            bean.data=newList;
          }
          return bean;
        },
        listFunc: (List<ClassCourseListItemBean> courseList) {
          // if(widget?.selectClassListBeanIndex?.length !=0 && widget?.selectClassListBeanIndex != null){
          //   widget?.selectClassListBeanIndex?.forEach((element) {
          //     selectCourseIndex.add(element?.id);
          //   });
          // }
          mList = courseList;
          if (mAddRecordClassList.length > 0) {
            mAddRecordClassList.forEach((element) {
              // if(element?.name!=""&&element?.name!=null){
              //
              // }
              mList?.insert(0, element);
            });
          }
          mList.forEach((element) {
            element.isSelect = false;
          });
          if (selectCourseIndex == null || selectCourseIndex.isEmpty) {
            return;
          }
          for (ClassCourseListItemBean itemBean in mList) {
            if (itemBean?.id == null || itemBean.id.isEmpty) {
              continue;
            }
            if (selectCourseIndex.indexOf(itemBean.id) != -1) {
              itemBean.isSelect = true;
              selectListCourseItemBean.add(itemBean);
            }
          }

          if (_editCourseListController == null ||
              _editCourseListController.isEmpty) {
            return;
          }
          _editCourseListController?.forEach((controller) {
            ClassCourseListItemBean addItemBean = ClassCourseListItemBean();
            addItemBean.isEdit = true;
            addItemBean.controller = controller;
            mList?.insert(0, addItemBean);
          });
        },
        stateFunc: (CommonListPageWidgetState state) {
          mState = state;
        },
        itemBuilder: (BuildContext context, int index,
            ClassCourseListItemBean itemBean) {
          if (itemBean == null) return Container();

          if (itemBean?.isEdit ?? false) {
            return _addCourseListRow(context, index, itemBean);
          }

          return _toListItemWidget(context, index, itemBean);
        },
        //分割器构造器
        separatorBuilder: (context, int index, _) {
          return Container(
            height: 0.5,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: const EdgeInsets.only(left: 15),
            child: Container(
              color: Color(0xFF303546),
            ),
          );
          // return divider;
        },
        placeHolderFunc: (List<ClassCourseListItemBean> list, Widget child,
            VoidCallback onRefresh) {
          return VgPlaceHolderStatusWidget(
            emptyStatus: list == null || list.isEmpty,
            emptyOnClick: () => onRefresh(),
            child: child,
          );
        },
        netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
        httpType: VgHttpType.post,
      ),
    );
  }

  Widget _addCourseListRow(
      BuildContext context, int index, ClassCourseListItemBean itemBean) {
    return GestureDetector(
      onTap: () {
        if (itemBean?.isSelect == null || itemBean?.isSelect == "")
          itemBean?.isSelect = false;
        itemBean?.isSelect = !itemBean?.isSelect;
        setState(() {});
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean?.isSelect ?? false
                  ? AssetImage("images/common_unselect_ico.png")
                  : AssetImage("images/common_selected_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: VgTextField(
                autofocus: true,
                maxLines: 1,
                controller: itemBean.controller,
                onChanged: (String editCourse) {
                  // itemBean?.name= _editCourseController?.text;
                  // print("输出长度：${_editCourseListController.length}");
                  String editListText = "";
                  for (TextEditingController item
                      in _editCourseListController) {
                    editListText += item.text.toString();
                  }
                  if (_editCourseListController.length != 0 &&
                      editListText.trim() != null &&
                      editListText.trim() != "") {
                    isLightUp = true;
                  } else {
                    isLightUp = false;
                  }
                  setState(() {});
                },
                decoration: InputDecoration(
                  border: InputBorder.none,
                  counterText: "",
                  contentPadding: const EdgeInsets.only(bottom: 2),
                  hintText: "请输入班级名",
                  hintStyle: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50(),
                      fontSize: 14),
                ),
                style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, ClassCourseListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        itemBean.isSelect = !itemBean.isSelect;
        if (itemBean.isSelect) {
          selectCourseIndex.add(itemBean.id);
          selectListCourseItemBean.add(itemBean);
        } else {
          selectCourseIndex.remove(itemBean.id);
          selectListCourseItemBean.remove(itemBean);
        }
        // print(selectCourseIndex.toString());
        setState(() {
          checkSave();
        });
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean.isSelect ?? false
                  ? AssetImage("images/common_selected_ico.png")
                  : AssetImage("images/common_unselect_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Container(
              width: (VgToolUtils.getScreenWidth()/4)*3,
              child: Text(
                itemBean?.name ?? "",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _editCourseWidget() {
    return Container(
      height: 50,
      color: Colors.redAccent,
      child: VgTextField(),
    );
  }

  Widget _addCourseListWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        _addRowCourse();
      },
      child: Container(
        height: 50,
        padding: const EdgeInsets.only(left: 7),
        alignment: Alignment.centerLeft,
        child: Text(
          "+添加",
          style: TextStyle(color: Color(0xFF1890FF), fontSize: 14),
          textAlign: TextAlign.left,
        ),
      ),
    );
  }

  void _addRowCourse() {
    TextEditingController _editCourseController = new TextEditingController();
    ClassCourseListItemBean addItemBean = ClassCourseListItemBean();
    addItemBean.isEdit = true;
    addItemBean.controller = _editCourseController;

    _editCourseListController.insert(0, _editCourseController);
    mList?.insert(0, addItemBean);
    mState?.data = mList;
    mAddRecordClassList.add(addItemBean);
    mState.setState(() {});
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "班级",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isLightUp || widget.fromEditUser,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if (isLightUp || widget.fromEditUser) {
            _httpSave();
          }
        },
      ),
    );
  }

  void _httpSave() {
    if (_editCourseListController != null &&
        _editCourseListController?.length > 0) {
      String textList = "";
      for (int i = 0; i < _editCourseListController?.length; i++) {
        if (_editCourseListController[i]?.text?.trim() == "") {
          _editCourseListController.removeAt(i);
        }
      }
      for (int i = 0; i < _editCourseListController?.length; i++) {
        if (_editCourseListController?.length != 0) {
          textList += _editCourseListController[i]?.text?.trim() + ",";
        }
      }
      if (textList == "") {
        if (_editCourseListController?.length == 0) {
          if (selectListCourseItemBean?.length != 0 &&
              selectListCourseItemBean != null) {
            for (int i = 0; i < selectListCourseItemBean?.length; i++) {
              if (selectListCourseItemBean[i]?.name == "") {
                selectListCourseItemBean?.removeAt(i);
              }
              listClassItemBean.add(selectListCourseItemBean[i]);
            }
          }
          return RouterUtils.pop(context, result: listClassItemBean);
        }
      }
      VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
          params: {
            "authId": UserRepository.getInstance().authId ?? "",
            "name": textList.substring(0, textList.length - 1) ?? "",
            "type": _classType,
          },
          callback: BaseCallback(onSuccess: (dynamic val) {
            UserSelectSortSaveResponseBean successBean =
                UserSelectSortSaveResponseBean.fromMap(val);
            if (successBean == null ||
                successBean.data == null ||
                successBean.data.isEmpty) {
              VgToastUtils.toast(context, "课程添加返回值错误");
              return;
            }

            successBean.data.forEach((element) {
              ClassCourseListItemBean classCourseListItemBean =
                  ClassCourseListItemBean();
              classCourseListItemBean?.name = element?.name;
              classCourseListItemBean?.id = element?.id;
              listClassItemBean.add(classCourseListItemBean);
            });
            //接收数据，selectCourseIndex进行for循环对比，拿出选中的指返回给上一界面
            VgToastUtils.toast(context, "保存成功");
            popResult();
          }, onError: (String e) {
            VgToastUtils.toast(context, "添加数据错误");
            return;
          }));
      // for(CourseClassListItemBean item in mList){
      //   print("gz2:::${item.name} :: ${item.id}  ::  ${item.isSelect} ::  ${item.isEdit}");
      // }
    } else {
      popResult();
    }
  }

  ///返回选择结果
  void popResult() {
    if (selectListCourseItemBean?.length != 0 &&
        selectListCourseItemBean != null) {
      for (int i = 0; i < selectListCourseItemBean?.length; i++) {
        listClassItemBean.add(selectListCourseItemBean[i]);
      }
    }
    VgToastUtils.toast(context, "保存成功");
    RouterUtils.pop(context, result: listClassItemBean);
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String classText) {
          searchName = classText;
          mState?.viewModel?.refresh();
        },
      ),
    );
  }

  void checkSave() {
    isLightUp =
        selectListCourseItemBean.isNotEmpty || selectCourseIndex.isNotEmpty;
  }
}
